package com.he.springbootweb.controller;

import com.he.springbootweb.dao.DepartmentDao;
import com.he.springbootweb.dao.EmployeeDao;
import com.he.springbootweb.pojo.Department;
import com.he.springbootweb.pojo.Employee;
import com.sun.org.apache.xpath.internal.operations.Mod;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.Collection;

@Controller
public class EmployeeController {

    //本来调用service，但是这里只有dao，所以教学用，思想一样
    @Autowired
    EmployeeDao employeeDao;

    @Autowired
    DepartmentDao departmentDao;

    @RequestMapping("/emps")
    public String list(Model model){
        Collection<Employee> employees = employeeDao.getAll();
         model.addAttribute("emps", employees);
         return "/emp/list";
    }

    @GetMapping("/emp")
    public String toAdd(Model model){
        //查出所有部门的信息
        Collection<Department> departments = departmentDao.getDepartment();
        model.addAttribute("departments",departments);
        return "emp/add";
    }

    @PostMapping("/emp")
    public String addEmp(Employee employee){
        employeeDao.save(employee);
        return "redirect:/emps";
    }

    //去员工的编辑页面
    @GetMapping("/emp/{id}")
    //@PathVariable接收请求路径中占位符的值
    public String toUpdateEmp(@PathVariable("id")Integer id,Model model){
        //编辑员工页面，就要首先查出员工页面
        Employee employee = employeeDao.getEmployeeById(id);
        model.addAttribute("emp",employee);
        Collection<Department> departments = departmentDao.getDepartment();
        model.addAttribute("departments",departments);
        return "/emp/update";
    }

    //修改的提交
    @PostMapping("/updateEmp")
    public String UpdateEmp(Employee employee){
        employeeDao.save(employee);
        return "redirect:/emps";
    }

    //删除员工信息
    @GetMapping("/delemp/{id}")
    public String DeleteEmp(@PathVariable("id")Integer id){
        employeeDao.deleteEmployeeById(id);
        return "redirect:/emps";
    }




}
